﻿using System.Collections.Generic;
using System.IO;

namespace StudentsInBinaryFile
{
    public class Student
    {
        private string firstName;
        private string lastName;
        private int fn;

        public Student(string firstName, string lastName, int fn)
        {
            this.FirstName = firstName;
            this.LastName = lastName;
            this.Fn = fn;
        }

        public string FirstName
        {
            get
            {
                return firstName;
            }
            private set
            {
                firstName = value;
            }
        }

        public string LastName
        {
            get
            {
                return lastName;
            }
            private set
            {
                lastName = value;
            }
        }

        public int Fn
        {
            get
            {
                return fn;
            }
            private set
            {
                fn = value;
            }
        }

        public static void AddStudentToFile(BinaryWriter writer, Student student)
        {
            writer.Write(student.Fn);
            writer.Write(student.FirstName);
            writer.Write(student.LastName);
        }

        public static List<Student> ReadAllStudentsFromFile(string fileName)
        {
            var studentsInFile = new List<Student>();
            using (var reader = new BinaryReader(File.Open(fileName, FileMode.OpenOrCreate)))
            {
                while (reader.BaseStream.Position < reader.BaseStream.Length)
                {
                    int fn = reader.ReadInt32();
                    string firstName = reader.ReadString();
                    string lastName = reader.ReadString();
                    studentsInFile.Add(new Student(firstName, lastName, fn));
                }
            }
            return studentsInFile;
        }

        public static void RemoveStudentFromFile(string fileName, int facultyNumber)
        {
            List<Student> allStudents = ReadAllStudentsFromFile(fileName);
            File.Delete(fileName);
            using (var writer = new BinaryWriter(File.Open(fileName, FileMode.Append, FileAccess.Write)))
            {
                foreach (Student student in allStudents)
                {
                    if (student.Fn != facultyNumber)
                    {
                        AddStudentToFile(writer, student);
                    }
                }
            }
        }

        public override string ToString()
        {
            return string.Format("{0,10}| {1} {2}", Fn, FirstName, LastName);
        }
    }
}
